<template>
  <div class="main-page">
    <el-row type="flex" justify="end">
      <el-button
        type="primary"
        size="medium"
        icon="el-icon-plus"
        @click="handleCreateUser"
      >
        新建角色
      </el-button>
    </el-row>
    <PageContent
      ref="pageContent"
      v-loading="loading"
      :form-data="formData"
      :content-table-config="contentConfig"
    >
      <template #operate="{ row }">
        <el-button
          type="text"
          size="small"
          icon="el-icon-edit"
          @click="handleEdit(row)"
        >
          编辑
        </el-button>
        <el-button
          type="text"
          size="small"
          icon="el-icon-delete"
          class="delete-btn"
          @click="handleDelete(row)"
        >
          删除
        </el-button>
      </template>
    </PageContent>

    <PageModal
      :modal-form-data="modalFormData"
      :modal-form-config="modalFormConfig"
      :visible.sync="dialogVisible"
      title="新建角色"
      :btn-loading="confirmBtnLoading"
      @confirm="handleConfirm"
    >
      <div class="menu-tree">
        <el-tree
          ref="elTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        />
      </div>
    </PageModal>
  </div>
</template>

<script>
import { contentConfig } from "./config/content.config";
import { searchFormConfig } from "./config/search.config";
import { modalFormConfig } from "./config/modal.config";
import {
  fetchRoleDetail,
  fetchMenuList,
  fetchSaveRole,
  fetchDeleteRole,
  fetchRoleList
} from "@/api/useManage";

export default {
  name: "Role",
  data() {
    return {
      loading: false,
      menus: [],
      contentConfig,
      searchFormConfig,
      modalFormConfig,
      btnLoading: false,
      confirmBtnLoading: false,
      dialogVisible: false,
      formData: {}, // 搜索表单数据
      modalFormData: {
        menuIds: [],
      }, // 模态框表单数据
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.loading = true;
      fetchRoleList()
        .then((res) => {
          this.contentConfig.dataList = res.data;
          this.$refs.pageContent.queryTblMain();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSearch() {
      this.getUserList();
    },
    handleCreateUser() {
      this.modalFormData = {};
      fetchMenuList().then((res) => {
        this.menus = res.data;
      });
      this.dialogVisible = true;
    },
    async handleEdit({ id }) {
  await fetchMenuList().then((res) => {
    this.menus = res.data;
  });
  fetchRoleDetail(id).then((res) => {
    this.modalFormData = { ...this.modelFormData, ...res.data };
    this.$nextTick(() => {
      // 修改后的节点处理逻辑
      const validKeys = this.modalFormData.menuIds.filter(id => 
        this.$refs.elTreeRef.getNode(id) // 过滤有效节点
      );
      validKeys.forEach((item) => {
        const node = this.$refs.elTreeRef.getNode(item);
        if (node && node.isLeaf) { // 添加空值校验
          this.$refs.elTreeRef.setChecked(node, true);
        }
      });
    });
  });
  this.dialogVisible = true;
},
    handleCheckChange(data1, data2) {
      const checkedKeys = data2.checkedKeys;
      const halfCheckedKeys = data2.halfCheckedKeys;
      const menuList = [...checkedKeys, ...halfCheckedKeys];
      this.modalFormData.menuIds = menuList;
    },
    handleDelete({ id }) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          fetchDeleteRole(id).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.handleSearch();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleConfirm(data) {
      this.confirmBtnLoading = true;
      const params = { ...this.modalFormData, ...data };
      fetchSaveRole(params)
        .then(() => {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.handleSearch();
        })
        .finally(() => {
          this.confirmBtnLoading = false;
          this.dialogVisible = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.main-page {
  margin-top: 15px;
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
